// src/utils/request.js
import axios from 'axios'
import { Message } from 'element-ui'

const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL || '',
  timeout: 60000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    config.headers = {
      'Content-Type': 'application/json'
    }
    return config
  },
  error => {
    console.error('Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (response.status === 200) {
      return res
    }
    Message.error(res.message || `Request failed with status: ${response.status}`)
    return Promise.reject(new Error(res.message || 'Error'))
  },
  error => {
    console.error('Response Error:', error)

    let errorMessage = 'Request failed'
    if (error.response) {
      switch (error.response.status) {
        case 401:
          errorMessage = 'Authentication required'
          break
        case 403:
          errorMessage = 'Permission denied'
          break
        case 500:
          errorMessage = 'Server error'
          break
      }
    } else if (error.message.includes('timeout')) {
      errorMessage = 'Request timeout'
    }

    Message.error(errorMessage)
    return Promise.reject(error)
  }
)

// 封装核心请求方法
export function request(options) {
  const method = options.method.toLowerCase() || 'get'

  const config = {
    url: options.url,
    method,
    headers: options.headers || {}
  }

  // 根据请求方法分配参数位置
  if (method === 'get' || method === 'delete') {
    config.params = options.data
  } else {
    config.data = options.data
  }

  return service(config)
}

// 快捷方法
export function get(url, params = {}, headers = {}) {
  return request({ url, method: 'get', data: params, headers })
}

export function post(url, data = {}, headers = {}) {
  return request({ url, method: 'post', data, headers })
}


export default {
  request,
  get,
  post,
}